package com.example.first.adapters;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.first.R;
import com.example.first.modle.ApiResponse;
import com.example.first.modle.CartItem;
import com.example.first.modle.Dish;
import com.example.first.modle.DishFlavor;
import com.example.first.modle.ShoppingCart;
import com.example.first.services.ApiService;
import com.example.first.utils.RetrofitClient;

import java.math.BigDecimal;
import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

public class DishAdapter extends BaseAdapter {
    private Context context;
    private List<Dish> dishes;
    private List<CartItem> cartItems;
    private Activity parentActivity;

    public DishAdapter(Context context, List<Dish> dishes, List<CartItem> cartItems,Activity activity) {
        this.context = context;
        this.dishes = dishes;
        this.cartItems = cartItems;
        this.parentActivity=activity;
    }



    @Override
    public int getCount() {
        return dishes.size();
    }

    @Override
    public Object getItem(int position) {
        return dishes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d("DishAdapter", "getView called for position: " + position);
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.dish_item, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        Dish dish = dishes.get(position);
        viewHolder.nameTextView.setText(dish.getName());
        viewHolder.priceTextView.setText("￥"+ dish.getPrice());
        viewHolder.salesTextView.setText(dish.getDescription());


        // 使用Glide加载图片
        Glide.with(context)
                .load(dish.getImage())
                .into(viewHolder.dishImageView);

/*        if (dish.getFlavors() != null && !dish.getFlavors().isEmpty()) {
            // 如果有口味，显示选择口味按钮
            viewHolder.addCartButton.setVisibility(View.GONE);
            viewHolder.chooseFlavorButton.setVisibility(View.VISIBLE);


        } else {
            // 如果没有口味，显示加入购物车按钮
            viewHolder.addCartButton.setVisibility(View.VISIBLE);
            viewHolder.addCartButton.setVisibility(View.VISIBLE);

        }*/


        if(dish.getFlavors().isEmpty()){
            viewHolder.addCartButton.setVisibility(View.VISIBLE);
            viewHolder.chooseFlavorButton.setVisibility(View.GONE);
            for (CartItem cartItem : cartItems) {
                if(cartItem.getDishId().equals(dish.getId())){
                    if(cartItem.getNumber()>0){
                        //如果购物车中的数量大于零
                        viewHolder.number.setText(String.valueOf(cartItem.getNumber()));
                        viewHolder.number.setVisibility(View.VISIBLE);
                        viewHolder.subCartButton.setVisibility(View.VISIBLE);
                    }
                }
            }
        }else {
            viewHolder.chooseFlavorButton.setVisibility(View.VISIBLE);
            viewHolder.addCartButton.setVisibility(View.GONE);
        }

        //设置加的点击事件
        viewHolder.addCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShoppingCart shoppingCart=new ShoppingCart();
                shoppingCart.setDishId(dish.getId());
                ApiService apiService=RetrofitClient.getApiService();
                Call<ApiResponse<String>> call = apiService.addCart(shoppingCart);
                call.enqueue(new retrofit2.Callback<ApiResponse<String>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                        if (response.isSuccessful() && response.body() != null){
                            if (response.body().getCode()==1){
                                Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
                                Integer number=Integer.valueOf(viewHolder.number.getText().toString());
                                number++;
                                viewHolder.number.setText(String.valueOf(number));
                                viewHolder.number.setVisibility(View.VISIBLE);
                                viewHolder.subCartButton.setVisibility(View.VISIBLE);

                                TextView viewById = parentActivity.findViewById(R.id.text_view);
                                String priceText = viewById.getText().toString().replace("￥", "").trim();
                                BigDecimal price = new BigDecimal(priceText);
                                price=price.add(dish.getPrice());
                                viewById.setText("￥"+price.toString());

                            }else {
                                Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                        Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        //设置减的点击事件
        viewHolder.subCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShoppingCart shoppingCart=new ShoppingCart();
                shoppingCart.setDishId(dish.getId());
                ApiService apiService=RetrofitClient.getApiService();
                Call<ApiResponse<String>> call = apiService.subCart(shoppingCart);
                call.enqueue(new retrofit2.Callback<ApiResponse<String>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                        if (response.isSuccessful() && response.body() != null){
                            if (response.body().getCode()==1){
                                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                                Integer number=Integer.valueOf(viewHolder.number.getText().toString());
                                number--;
                                //如果数量零,隐藏减按钮和数字
                                if(number==0){
                                    viewHolder.number.setVisibility(View.GONE);
                                    viewHolder.subCartButton.setVisibility(View.GONE);
                                }
                                viewHolder.number.setText(String.valueOf(number));
                                TextView viewById = parentActivity.findViewById(R.id.text_view);
                                String priceText = viewById.getText().toString().replace("￥", "").trim();
                                BigDecimal price = new BigDecimal(priceText);
                                price=price.subtract(dish.getPrice());
                                viewById.setText("￥"+price.toString());


                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                        Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        // 设置按钮的点击事件
        viewHolder.chooseFlavorButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 处理选择口味的逻辑
                Dialog dialog =new Dialog(context,R.style.DialogTheme);
                dialog.setContentView(R.layout.select_dish_dialog);

                RecyclerView flavorRecyclerView=dialog.findViewById(R.id.flavorRecyclerView);
                flavorRecyclerView.setLayoutManager(new LinearLayoutManager(context));

                List<DishFlavor> flavors=dish.getFlavors();

                FlavorAdapter flavorAdapter=new FlavorAdapter(context,flavors);
                flavorRecyclerView.setAdapter(flavorAdapter);
                flavorAdapter.setDishFlavors(flavors);
                flavorAdapter.notifyDataSetChanged();


                //设置名字和价格
                TextView dishNameTextView=dialog.findViewById(R.id.dishNameTextView);
                TextView dishPriceTextView=dialog.findViewById(R.id.priceTextView);
                dishNameTextView.setText(dish.getName());
                dishPriceTextView.setText("￥"+ dish.getPrice());

                //设置Dialog的宽度和高度
                WindowManager.LayoutParams layoutParams =dialog.getWindow().getAttributes();
                layoutParams.copyFrom(dialog.getWindow().getAttributes());

                // 设置宽度为屏幕三分之二左右,居中
                layoutParams.width = context.getResources().getDisplayMetrics().widthPixels * 4 / 5;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                layoutParams.gravity = Gravity.CENTER;
                dialog.getWindow().setAttributes(layoutParams);



                Button addCartButton=dialog.findViewById(R.id.addToCartButton);



                //加入购物车按钮点击事件
                addCartButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //拿到口味信息
                        String selectedButtonText=flavorAdapter.getSelectedButtonText();

                        //Log.d("DishAdapter", "Selected button text: " + selectedButtonText);测试

                        ShoppingCart shoppingCart=new ShoppingCart();
                        shoppingCart.setDishId(dish.getId());
                        shoppingCart.setDishFlavor(selectedButtonText);


                        ApiService apiService=RetrofitClient.getApiService();
                        Call<ApiResponse<String>> call=apiService.addCart(shoppingCart);
                        call.enqueue(new retrofit2.Callback<ApiResponse<String>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<String>> call, retrofit2.Response<ApiResponse<String>> response) {
                                if(response.isSuccessful() && response.body()!=null){
                                    if(response.body().getCode()==1){
                                        Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();

                                        TextView viewById = parentActivity.findViewById(R.id.text_view);
                                        String priceText = viewById.getText().toString().replace("￥", "").trim();
                                        BigDecimal price = new BigDecimal(priceText);
                                        price=price.add(dish.getPrice());
                                        viewById.setText("￥"+price.toString());

                                        //关闭Dialog
                                        dialog.dismiss();
                                    }else {
                                        Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                    }

                                }else {
                                    Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                                //处理失败情况
                                t.printStackTrace();
                            }
                        });


                    }

                });



                dialog.show();

            }
        });


        return convertView;
    }

    public void setDishes(List<Dish> dishes, List<CartItem> cartItems) {
        this.dishes = dishes;
        this.cartItems = cartItems;
    }

    static class ViewHolder {
        TextView nameTextView;
        TextView priceTextView;
        ImageView dishImageView;
        Button chooseFlavorButton;
        ImageButton addCartButton;
        TextView salesTextView;
        ImageButton subCartButton;
        TextView number;

        ViewHolder(View view) {
            nameTextView = view.findViewById(R.id.nameTextView);
            priceTextView = view.findViewById(R.id.priceTextView);
            chooseFlavorButton = view.findViewById(R.id.chooseButton);
            addCartButton = view.findViewById(R.id.addCartButton);
            dishImageView = view.findViewById(R.id.dishImageView);
            salesTextView = view.findViewById(R.id.salesTextView);
            subCartButton = view.findViewById(R.id.sub_cart_button);
            number = view.findViewById(R.id.dish_number);
        }
    }
}
